import customizedError from "./Error/customizedError.js";
import * as customizedErrorCode from "./Error/customizedErrorCode.js";
import { AJAX } from "./helper.js";
import { API_URL } from "./config.js";

export const state = {};

export const submitForm = async function (rawForm) {
  try {
    const form = Object.entries(rawForm);
    // 1. 进行数据校验
    checkForm(form);
    // 2. 整理数据
    const uploadForm = createFormObject(rawForm);
    // 3. 发起请求
    const res = await AJAX(API_URL, uploadForm);
    if (res.code !== 200) {
      throw new customizedError(customizedErrorCode.SUBMIT_FAIL);
    }
    // 4. 保存提交状态
    state.form = uploadForm;
    persistSubmitForm(uploadForm);
  } catch (error) {
    throw error;
  }
};

const checkForm = function (form) {
  try {
    for (const [key, value] of form) {
      // 1. 判空
      if (value.trim() === "") {
        throw new customizedError(customizedErrorCode.INPUT_BLANK);
      }

      // 2. 检测输入是否符合格式
      let rg = "";
      switch (key) {
        case "name":
          rg = /^[^0-9\s]{2,15}$/;
          break;
        case "studentID":
          rg = /^[\d]{10}/;
          break;
        case "phone":
          rg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
          break;
        case "email":
          rg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
          break;
      }
      if (rg !== "" && !rg.test(value)) {
        throw new customizedError(customizedErrorCode.INPUT_NOT_MATCHED);
      }

      // 3. 检测长度是否过长。
      if (key === "plan" && value.length > 255)
        throw new customizedError(customizedErrorCode.INPUT_TOO_LONG);
    }
  } catch (error) {
    throw error;
  }
};

const createFormObject = function (rawForm) {
  return {
    name: rawForm.name,
    studentID: rawForm.studentID,
    phone: rawForm.phone,
    majority: +rawForm.majority,
    email: rawForm.email,
    grade: rawForm.grade,
    experience: rawForm.experience,
    plan: rawForm.plan,
  };
};

const persistSubmitForm = function (form) {
  localStorage.setItem("form", JSON.stringify(form));
};

const init = function () {
  state.form = JSON.parse(localStorage.getItem("form")) ?? "";
};
init();
